package com.ruoyi.web.controller.invoice.dingding;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalktodo_1_0.models.CreateTodoTaskHeaders;
import com.aliyun.dingtalktodo_1_0.models.CreateTodoTaskRequest;
import com.aliyun.dingtalktodo_1_0.models.CreateTodoTaskResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiMessageCorpconversationSendbytemplateRequest;
import com.dingtalk.api.response.OapiMessageCorpconversationSendbytemplateResponse;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.dingmessage.impl.DingTodoService;
import com.ruoyi.system.domain.CorpInfo;
import com.ruoyi.system.domain.invoice.DingIssueMessage;
import com.ruoyi.system.domain.invoice.DingTodo;
import com.ruoyi.system.domain.invoice.InvoiceInfoDto;
import com.ruoyi.system.service.ICorpInfoService;
import com.ruoyi.system.service.impl.CorpTokenService;
import com.taobao.api.ApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 钉钉消息、待办接口
 */
@Api(tags = "钉钉代办消息接口")
@RestController
@AllArgsConstructor
@RequestMapping("invoice/ding")
public class DingMessageController {

    private final DingTodoService dingTodoService;

    private final CorpTokenService corpTokenService;

    private final ICorpInfoService corpInfoService;

    /**
     * 使用 Token 初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public com.aliyun.dingtalktodo_1_0.Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalktodo_1_0.Client(config);
    }


    @ApiOperation(value = "发送开票待办给合作客户", httpMethod = "POST")

    @PostMapping("sendTodoByUserId")
    public AjaxResult sendTodoByUserId(@RequestBody DingTodo<InvoiceInfoDto> dingTodo) {
        com.aliyun.dingtalktodo_1_0.Client client = null;
        try {
            client = createClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        CreateTodoTaskHeaders createTodoTaskHeaders = new CreateTodoTaskHeaders();
        try {
            createTodoTaskHeaders.xAcsDingtalkAccessToken = corpTokenService.getCorpToken(dingTodo.getCorpId());


            CreateTodoTaskRequest.CreateTodoTaskRequestNotifyConfigs notifyConfigs = new CreateTodoTaskRequest.CreateTodoTaskRequestNotifyConfigs()
                    .setDingNotify("1");
            CreateTodoTaskRequest.CreateTodoTaskRequestContentFieldList contentFieldList0 = new CreateTodoTaskRequest.CreateTodoTaskRequestContentFieldList();
//            CreateTodoTaskRequest.CreateTodoTaskRequestDetailUrl detailUrl = new CreateTodoTaskRequest.CreateTodoTaskRequestDetailUrl()
//                    .setAppUrl("http://front.frp.hfjysj.com.cn:10012/")
//                    .setPcUrl("http://front.frp.hfjysj.com.cn:10012/");
            InvoiceInfoDto invoiceInfoDto = dingTodo.getData();
            // 检查是否有更新开票抬头信息
            CorpInfo corpInfo = corpInfoService.selectCorpInfoById(dingTodo.getCorpId());
            if (StringUtils.isBlank(corpInfo.getNssbh())) {
                corpInfo.setCorpName(invoiceInfoDto.getCorpName());
                corpInfo.setCorpAddress(invoiceInfoDto.getAddress());
                corpInfo.setAccount(invoiceInfoDto.getAccount());
                corpInfo.setTel(invoiceInfoDto.getTel());
                corpInfo.setNssbh(invoiceInfoDto.getNssbh());
                corpInfo.setIssuingBank(invoiceInfoDto.getIssuingBank());
                corpInfoService.updateCorpInfo(corpInfo);
            }
            String ln = "\r\n";
            String corpInvoiceInfo = String.join(",",
                    "企业名称：" + invoiceInfoDto.getCorpName() + ln,
                    "税号：" + invoiceInfoDto.getNssbh() + ln,
                    "企业地址：" + invoiceInfoDto.getAddress() + ln,
                    "电话：" + invoiceInfoDto.getTel() + ln,
                    "开户行：" + invoiceInfoDto.getIssuingBank() + ln,
                    "银行账户：" + invoiceInfoDto.getAccount() + ln,
                    "=================================" + ln);
//                     "<a href=\"http://front.frp.hfjysj.com.cn:10012/\" target=\"_blank\" rel=\"noopener noreferrer\">理解开票</a>"+ln);
            CreateTodoTaskRequest createTodoTaskRequest = new CreateTodoTaskRequest()
                    .setOperatorId(dingTodo.getCreatorId())
                    .setSourceId(UUID.randomUUID().toString())
                    .setSubject(invoiceInfoDto.getCorpName() + ": " + dingTodo.getSubject())
                    .setCreatorId(dingTodo.getCreatorId())
                    .setDescription(corpInvoiceInfo + "请根据以上信息开票")
                    .setDueTime(System.currentTimeMillis() + 86400000L)
                    .setExecutorIds(
                            Arrays.asList(dingTodo.getExecutorIds().split(","))
                    )
                    .setParticipantIds(
                            Arrays.asList(dingTodo.getParticipantIds().split(","))
                    )
//                    .setDetailUrl(detailUrl)
                    .setContentFieldList(java.util.Arrays.asList(
                            contentFieldList0
                    ))
                    .setIsOnlyShowExecutor(false)
                    .setPriority(20)
//                    .setDueTime()
                    .setNotifyConfigs(notifyConfigs);


            CreateTodoTaskResponse todoTaskResponse = client.createTodoTaskWithOptions(dingTodo.getCreatorId(), createTodoTaskRequest, createTodoTaskHeaders, new RuntimeOptions());
            AjaxResult result = AjaxResult.success("发送成功", todoTaskResponse.getBody());

            return result;
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                err.printStackTrace();
                return AjaxResult.error("发送失败:" + err.getMessage());

            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                err.printStackTrace();
                return AjaxResult.error("发送失败:" + err.getMessage());
            }

        }
        return AjaxResult.error("发送失败");
    }

    @PostMapping("sendIssueOaMessage")
    public AjaxResult sendIssueOaMessage(@RequestBody DingIssueMessage issueMessage) {
        CorpInfo corpInfo = corpInfoService.selectCorpInfoById(issueMessage.getCorpId());
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/sendbytemplate");
        OapiMessageCorpconversationSendbytemplateRequest req = new OapiMessageCorpconversationSendbytemplateRequest();
        req.setAgentId(corpInfo.getAgentId());
//        req.setDeptIdList("421897262");
        req.setUseridList(issueMessage.getToUserList());
        req.setTemplateId("eb4cf9bb6d1c450caea9ec7b36b0572b");


        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();

        msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
        String messageUrl = "http://front.frp.hfjy.com.cn:10012/invoice-preview?fpdm="+issueMessage.getFpdm()+"&fphm="+issueMessage.getFphm()+"&ids="+issueMessage.getId()+"&fplxdm="+issueMessage.getFplxdm();
        msg.getOa().setMessageUrl("dingtalk://dingtalkclient/action/openapp?corpid="+corpInfo.getCorpId()+"&container_type=work_platform&app_id="+corpInfo.getAgentId()+"&redirect_type=jump&redirect_url="+messageUrl);
//        msg.getOa().setPcMessageUrl(messageUrl);
        msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
        msg.getOa().getHead().setText("text");
        msg.getOa().getHead().setBgcolor("FFBBBBBB");

        msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
        msg.getOa().getBody().setContent("您有来自"+corpInfo.getCorpName()+"开具的发票");
        msg.getOa().getBody().setFileCount(issueMessage.getFileCount());
        msg.getOa().setStatusBar(new OapiMessageCorpconversationAsyncsendV2Request.StatusBar());
        msg.getOa().getBody().setRich(new OapiMessageCorpconversationAsyncsendV2Request.Rich());
        msg.getOa().getBody().getRich().setNum(issueMessage.getAmount());
        msg.getOa().getBody().getRich().setUnit("元");

        OapiMessageCorpconversationAsyncsendV2Request.Form corpName = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        corpName.setKey("corpName");
        corpName.setValue(corpInfo.getCorpName());

        OapiMessageCorpconversationAsyncsendV2Request.Form amount = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        amount.setKey("amount");
        amount.setValue(issueMessage.getAmount());

        OapiMessageCorpconversationAsyncsendV2Request.Form fileCount = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        fileCount.setKey("fileCount");
        fileCount.setValue(issueMessage.getFileCount());

        OapiMessageCorpconversationAsyncsendV2Request.Form fpdm = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        fpdm.setKey("fpdm");
        fpdm.setValue(issueMessage.getFpdm());

        OapiMessageCorpconversationAsyncsendV2Request.Form fphm = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        fphm.setKey("fphm");
        fphm.setValue(issueMessage.getFphm());

        OapiMessageCorpconversationAsyncsendV2Request.Form id = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        id.setKey("id");
        id.setValue(issueMessage.getId());

        OapiMessageCorpconversationAsyncsendV2Request.Form fplxdm = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        fplxdm.setKey("fplxdm");
        fplxdm.setValue(issueMessage.getFplxdm());

        OapiMessageCorpconversationAsyncsendV2Request.Form fplx = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        fplx.setKey("fplx");
        fplx.setValue(issueMessage.getFplx());

        OapiMessageCorpconversationAsyncsendV2Request.Form nssbh = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        nssbh.setKey("nssbh");
        nssbh.setValue(issueMessage.getNssbh());

        OapiMessageCorpconversationAsyncsendV2Request.Form address = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        address.setKey("address");
        address.setValue(issueMessage.getAddress());

        OapiMessageCorpconversationAsyncsendV2Request.Form issuingBank = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        issuingBank.setKey("issuingBank");
        issuingBank.setValue(issueMessage.getIssuingBank());

        OapiMessageCorpconversationAsyncsendV2Request.Form account = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        account.setKey("account");
        account.setValue(issueMessage.getAccount());

        OapiMessageCorpconversationAsyncsendV2Request.Form tel = new OapiMessageCorpconversationAsyncsendV2Request.Form();
        tel.setKey("tel");
        tel.setValue(issueMessage.getTel());

        ArrayList<OapiMessageCorpconversationAsyncsendV2Request.Form> objects = new ArrayList<>();
        objects.add(corpName);
        objects.add(amount);
//        objects.add(fileCount);
        objects.add(fpdm);
        objects.add(fphm);
        objects.add(id);
        objects.add(fplxdm);
        objects.add(fplx);
        objects.add(nssbh);
        objects.add(address);
        objects.add(issuingBank);
        objects.add(account);
        objects.add(tel);
        msg.getOa().getBody().setForm(objects);
        msg.setMsgtype("oa");
//        req.setData(JSONObject.toJSONString(objects));

        OapiMessageCorpconversationSendbytemplateResponse rsp = null;
        try {
            rsp = client.execute(req, corpTokenService.getCorpToken(corpInfo.getCorpId()));
            System.out.println(rsp.getBody());
            return AjaxResult.success("发送成功", rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
            return AjaxResult.error("发送失败");
        }
    }
}



